const sqlite3 = require("sqlite3").verbose();
const fs = require("fs");
const path = require("path");

const dbPath = path.resolve("./subme.db");
const sqlPath = path.resolve("./scripts/subme.sql");

const db = new sqlite3.Database(
  dbPath,
  sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
  (err) => {
    if (err) {
      return console.log("打开数据库失败：", err);
    }
    console.log("数据库打开成功");
  }
);

const rawSql = fs.readFileSync(sqlPath, { encoding: "utf-8" });
const sqls = rawSql.split(";");

// serialize 保证按顺序执行
db.serialize(() => {
  sqls
    .filter((s) => s.trim().length > 0)
    .forEach((sql) => {
      console.log("正在执行：", sql);
      db.run(sql, (err) => {
        if (err) {
          return console.log("执行SQL失败：", err);
        }
        console.log("执行成功");
        console.log();
      });
    });

  db.close((err) => {
    if (err) {
      return console.log("关闭数据库失败：", err);
    }
    console.log("数据库关闭成功");
  });
});
